package com.android.jingweiapp.util;

import android.net.Uri;

import com.facebook.binaryresource.BinaryResource;
import com.facebook.binaryresource.FileBinaryResource;
import com.facebook.cache.common.CacheKey;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.DraweeView;
import com.facebook.imagepipeline.core.ImagePipelineFactory;
import com.facebook.imagepipeline.request.ImageRequest;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by cwr on 2015/7/16 at 13:54.
 */
public class CommonUtil {

    private static String InputStreamTOString(InputStream in, String encoding) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] data = new byte[4096];
        int count;
        while ((count = in.read(data, 0, 4096)) != -1)
            outStream.write(data, 0, count);
        String str = new String(outStream.toByteArray(), encoding);
        in.close();
        outStream.close();
        return str;
    }

    public static String replace(String xml, Map<String, String> params) {
        String result = xml;
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String name = "\\$" + entry.getKey();
                Pattern pattern = Pattern.compile(name);
                Matcher matcher = pattern.matcher(result);
                if (matcher.find()) {
                    result = matcher.replaceAll(entry.getValue());
                }
            }
        }
        return result;
    }


    /**
     * 在draweeView中加载图片
     *
     * @param uri
     * @param draweeView
     */
    public static void loadPic(Uri uri, DraweeView draweeView) {
        Uri temp = null;
        try {
            temp = Uri.parse(uri.toString().replace(uri.getLastPathSegment(), URLEncoder.encode(uri.getLastPathSegment(), "utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        DraweeController controller;
        if (!hasCache(temp)) {
            controller = Fresco.newDraweeControllerBuilder()
                    .setUri(temp)
                    .setTapToRetryEnabled(true)
                    .setOldController(draweeView.getController())
                    .build();
        } else {
            controller = Fresco.newDraweeControllerBuilder()
                    .setUri(Uri.parse(getCachedImageOnDisk(temp).toURI().toString()))
                    .setTapToRetryEnabled(true)
                    .setOldController(draweeView.getController())
                    .build();
        }
        draweeView.setController(controller);
    }

    /**
     * 判断缓存中是否有图片
     *
     * @param loadUri
     * @return
     */
    private static boolean hasCache(Uri loadUri) {
        if (loadUri == null) {
            return false;
        }
        CacheKey cacheKey = MyCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(loadUri));
        return ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey);
    }

    /**
     * 获取磁盘缓存文件
     *
     * @param loadUri
     * @return
     */
    private static File getCachedImageOnDisk(Uri loadUri) {
        File localFile = null;
        if (loadUri != null) {
            CacheKey cacheKey = MyCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(loadUri));
            if (ImagePipelineFactory.getInstance().getMainDiskStorageCache().hasKey(cacheKey)) {
                BinaryResource resource = ImagePipelineFactory.getInstance().getMainDiskStorageCache().getResource(cacheKey);
                localFile = ((FileBinaryResource) resource).getFile();
            } else if (ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().hasKey(cacheKey)) {
                BinaryResource resource = ImagePipelineFactory.getInstance().getSmallImageDiskStorageCache().getResource(cacheKey);
                localFile = ((FileBinaryResource) resource).getFile();
            }
        }
        return localFile;
    }

}
